<script setup>
  import { ref } from 'vue'
  import card from '@/hqbadmin/tpl/card.vue'
  const listData = ref(window.listData ? JSON.parse(window.listData) : [])

  function getContent(item) {
    if (typeof item === 'object') {
      let str = ''
      item.map((d) => {
        str += ' || '
        for (let name in d) {
          str += `${name}: ${d[name]} `
        }
      })
      return str.substring(4)
    }
    return item
  }

  function getObjectStr(data, col) {
    let str = ''
    data.forEach(item => {
      // 拼接json数据, 增加 \t 为了不让表格显示科学计数法或者其他格式
      for (let key of col) {
        if (item[key] != undefined) {
          str = `${str + getContent(item[key]) + '\t'},`
        } else {
          str = `${str + '-' + '\t'},`
        }
      }
      str += '\n'
    })
    return str
  }
  function exportData() {
    const data = listData.value
    let col = ['agree', 'type', 'teamType', 'esgName', 'vEName', 'projectName', 'teamName', 'teamPhone', 'teamInfo', 'teacher', 'teamMember']
    let head = '是否同意,类型,团队类型,esg名称,ve名称,项目名称,团队名称,团队队长手机号,队长信息,指导老师,团队成员'
    let name = '比赛数据'
    let str = head ? head + '\n' : ''
    str += getObjectStr(data, col)

    // encodeURIComponent解决中文乱码
    const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str)
    const link = document.createElement("a")
    link.href = uri
    link.download = `${name + '.csv'}`
    link.click()
  }
</script>

<template>
  <div class="p-1 space-y-8 sm:p-4 bg-slate-50">
    <div>
      <button class="px-8 py-2 text-white transition bg-indigo-500 rounded hover:bg-indigo-600" @click="exportData">导出数据</button>
    </div>
    <!-- {{listData}} -->
    <div :item="d" v-for="d, i in listData" :key="i">
      <card :item="d" />
    </div>
  </div>
</template>

<style scoped>

</style>